/**
 * 数据管理器
 * 处理数据导入导出和初始化
 */

import indexedDBManager from './indexedDB';
import { message } from 'antd';

class DataManager {
  constructor() {
    this.initialized = false;
  }

  // 初始化数据库
  async initialize() {
    if (this.initialized) return;

    try {
      await indexedDBManager.init();
      this.initialized = true;
      console.log('Database initialized successfully');

      // 检查是否需要创建默认用户
      const currentUser = await this.getCurrentUser();
      if (!currentUser) {
        console.log('No current user found, creating default user...');
        await this.createDefaultUser();
      }
    } catch (error) {
      console.error('Database initialization failed:', error);
      throw error;
    }
  }

  // 创建默认用户
  async createDefaultUser() {
    try {
      await this.initialize();

      // 检查是否已有用户
      const users = await indexedDBManager.getAll('users');
      if (users.length > 0) {
        return users[0];
      }

      // 创建默认用户
      const defaultUser = {
        username: 'admin',
        email: 'admin@example.com',
        password: 'admin123',
        avatar: '',
        background: ''
      };

      const user = await indexedDBManager.createUser(defaultUser);

      // 创建默认文件夹
      await this.createDefaultFolders(user.uid);

      // 自动修复图标路径（以防万一）
      await this.fixIconPaths();

      return user;
    } catch (error) {
      console.error('Create default user failed:', error);
      throw error;
    }
  }

  // 创建默认文件夹
  async createDefaultFolders(uid) {
    const defaultFolders = [
      {
        uid,
        parentId: 0,
        name: '文档',
        x: 100,
        y: 100,
        icon: '/img/icon/folder.png',
        isStatic: true
      },
      {
        uid,
        parentId: 0,
        name: '图片',
        x: 200,
        y: 100,
        icon: '/img/icon/folder.png',
        isStatic: true
      },
      {
        uid,
        parentId: 0,
        name: '下载',
        x: 300,
        y: 100,
        icon: '/img/icon/folder.png',
        isStatic: true
      },
      {
        uid,
        parentId: 0,
        name: '音乐',
        x: 100,
        y: 200,
        icon: '/img/icon/folder.png',
        isStatic: true
      },
      {
        uid,
        parentId: 0,
        name: '视频',
        x: 200,
        y: 200,
        icon: '/img/icon/folder.png',
        isStatic: true
      }
    ];

    for (const folderData of defaultFolders) {
      await indexedDBManager.createFolder(folderData);
    }
  }

  // 获取当前用户
  async getCurrentUser() {
    try {
      await this.initialize();
      const uid = localStorage.getItem('currentUserId');
      if (!uid) return null;

      return await indexedDBManager.get('users', uid);
    } catch (error) {
      console.error('Get current user failed:', error);
      return null;
    }
  }

  // 设置当前用户
  async setCurrentUser(uid) {
    try {
      localStorage.setItem('currentUserId', uid);
    } catch (error) {
      console.error('Set current user failed:', error);
    }
  }

  // 用户登录
  async login(username, password) {
    try {
      await this.initialize();

      const user = await indexedDBManager.getUserByUsername(username);
      if (!user || user.password !== password) {
        throw new Error('用户名或密码错误');
      }

      await this.setCurrentUser(user.uid);
      return user;
    } catch (error) {
      console.error('Login failed:', error);
      throw error;
    }
  }

  // 用户注册
  async register(userData) {
    try {
      await this.initialize();

      // 检查用户名是否已存在
      const existingUser = await indexedDBManager.getUserByUsername(userData.username);
      if (existingUser) {
        throw new Error('用户名已存在');
      }

      // 检查邮箱是否已存在
      const existingEmail = await indexedDBManager.getUserByEmail(userData.email);
      if (existingEmail) {
        throw new Error('邮箱已存在');
      }

      const user = await indexedDBManager.createUser(userData);
      await this.setCurrentUser(user.uid);

      // 为新用户创建默认文件夹
      await this.createDefaultFolders(user.uid);

      return user;
    } catch (error) {
      console.error('Register failed:', error);
      throw error;
    }
  }

  // 更新用户信息
  async updateUser(updateData) {
    try {
      const currentUser = await this.getCurrentUser();
      if (!currentUser) {
        throw new Error('未登录');
      }

      return await indexedDBManager.updateUser(currentUser.uid, updateData);
    } catch (error) {
      console.error('Update user failed:', error);
      throw error;
    }
  }

  // 获取桌面文件夹数据
  async getDesktopFolders() {
    try {
      const currentUser = await this.getCurrentUser();
      if (!currentUser) return [];

      const folders = await indexedDBManager.getFoldersByParent(0, currentUser.uid);
      const files = await indexedDBManager.getFilesByFolder(0, currentUser.uid);

      return [...folders, ...files];
    } catch (error) {
      console.error('Get desktop folders failed:', error);
      return [];
    }
  }

  // 导出数据
  async exportData() {
    try {
      const currentUser = await this.getCurrentUser();
      if (!currentUser) {
        throw new Error('未登录');
      }

      const data = await indexedDBManager.exportAllData(currentUser.uid);

      // 创建下载链接
      const blob = new Blob([data], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `win11-desktop-backup-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      message.success('数据导出成功');
    } catch (error) {
      console.error('Export data failed:', error);
      message.error('数据导出失败');
    }
  }

  // 导入数据
  async importData(file) {
    try {
      const currentUser = await this.getCurrentUser();
      if (!currentUser) {
        throw new Error('未登录');
      }

      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = async (e) => {
          try {
            const success = await indexedDBManager.importAllData(e.target.result, currentUser.uid);
            if (success) {
              message.success('数据导入成功');
              resolve(success);
            } else {
              throw new Error('导入失败');
            }
          } catch (error) {
            message.error('数据导入失败');
            reject(error);
          }
        };
        reader.onerror = () => {
          message.error('文件读取失败');
          reject(new Error('File read failed'));
        };
        reader.readAsText(file);
      });
    } catch (error) {
      console.error('Import data failed:', error);
      message.error('数据导入失败');
      throw error;
    }
  }

  // 登出
  async logout() {
    try {
      localStorage.removeItem('currentUserId');
      message.success('已登出');
    } catch (error) {
      console.error('Logout failed:', error);
    }
  }

  // 修复图标路径（用于修复重构后的图标路径问题）
  async fixIconPaths() {
    try {
      const currentUser = await this.getCurrentUser();
      if (!currentUser) return;

      // 更新文件夹图标路径
      const folders = await indexedDBManager.getAll('folders');
      for (const folder of folders.filter(f => f.uid === currentUser.uid)) {
        if (folder.icon && !folder.icon.startsWith('/img/')) {
          let newIconPath = folder.icon;
          if (folder.icon === 'folder.png') {
            newIconPath = '/img/icon/folder.png';
          } else if (folder.icon === 'markdown.ico') {
            newIconPath = '/img/icon/markdown.ico';
          } else {
            newIconPath = '/img/icon/' + folder.icon;
          }
          await indexedDBManager.updateFolder(folder.fid, { icon: newIconPath });
        }
      }

      // 更新文件图标路径
      const files = await indexedDBManager.getAll('files');
      for (const file of files.filter(f => f.uid === currentUser.uid)) {
        if (file.icon && !file.icon.startsWith('/img/')) {
          const newIconPath = file.icon === 'folder.png' ? '/img/icon/folder.png' : file.icon;
          await indexedDBManager.updateFile(file.fid, { icon: newIconPath });
        }
      }

      console.log('图标路径修复完成');
      return true;
    } catch (error) {
      console.error('修复图标路径失败:', error);
      return false;
    }
  }

  // 清除所有用户数据（用于重置）
  async clearAllData() {
    try {
      const currentUser = await this.getCurrentUser();
      if (!currentUser) return;

      await indexedDBManager.clearUserData(currentUser.uid);
      localStorage.clear();
      console.log('所有数据已清除');
      return true;
    } catch (error) {
      console.error('清除数据失败:', error);
      return false;
    }
  }

  // 获取所有应用数据
  async getAllData() {
    try {
      const currentUser = await this.getCurrentUser();
      if (!currentUser) {
        throw new Error('未登录');
      }

      const data = await indexedDBManager.exportAllData(currentUser.uid);
      return JSON.parse(data);
    } catch (error) {
      console.error('Get all data failed:', error);
      throw error;
    }
  }
}

// 创建全局实例
const dataManager = new DataManager();

export default dataManager;
